iT邦幫忙

1

ajax+aspx(回傳object)

  • 分享至 

  • xImage
  •  

後端回傳object
前端讀取後端傳回的object.如何讀取?

#後端
新增aspx,拿掉html,只留

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication2.aspx._object" %>

.cs

        protected void Page_Load(object sender, EventArgs e)
        {
            xx xx = new xx() { a = "123", b = "333" };
            
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string ret = serializer.Serialize(xx);
         
            Response.Write(ret);
            Response.End();
        }

#前端
新增html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="../js/jquery-3.2.1.js" type="text/javascript"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <div id="result1"></div>
    <div id="result2"></div>
    <div id="result3"></div>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "WebForm2.aspx",
                type: 'POST', 
                success: function (data) {
                    $('#result1').text(data);
                    var myarray = $.parseJSON(data);
                    $('#result2').text(myarray.a); 
                    $('#result3').text(myarray.b); 
                },
                error: function (err) {
                    console.log("err:");
                    console.log(err);
                    alert(err);
                }
            });
        });
    </script>

</body>
</html>

#Run
https://ithelp.ithome.com.tw/upload/images/20171017/201067644Tmr7QO9wh.png

進階
告訴ajax,傳來的是json,就會自動轉成object

   <script>
       $(document).ready(function () {
           $.ajax({
               url: "WebForm2.aspx",
               type: 'POST',
               dataType: 'json',
               success: function (data) {
                   $('#result1').text(data);
                   var myarray = data;
                   //var myarray = $.parseJSON(data);
                   $('#result2').text(myarray.a); 
                   $('#result3').text(myarray.b); 
               },
               error: function (err) {
                   console.log("err:");
                   console.log(err);
                   alert(err);
               }
           });
       });
   </script> 

#Run
https://ithelp.ithome.com.tw/upload/images/20171017/201067649GtZhg3RbW.png


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言